import imUtils from './im'
let sdkwx = uni.requireNativePlugin("TX-IM");
let message = uni.requireNativePlugin("TXIM-Message");
let conversation = uni.requireNativePlugin("TXIM-Conversation");
let group = uni.requireNativePlugin("TXIM-Group");
let friendship = uni.requireNativePlugin("TXIM-Friendship");
console.log({
    sdkwx,
    message,
    conversation,
    group,
    friendship
})
let im = {
    sdkAppId: 1400486110,
    ...sdkwx,
    sdkwx,
    message,
    conversation,
    group,
    friendship,
    _p: (cb) => new Promise(cb),
    _filePathToLocal: file => {
        if (file.substr(0, 4) === '/var') {
            return file
        }
        return plus.io.convertLocalFileSystemURL(file)
    },
    _filePathPrefix (file) {
        if (['file://', '/'].indexOf(file) === 0) {
            return 'file://' + file.replace('file://', '')
        } else {
            return im._filePathPrefix(plus.io.convertLocalFileSystemURL(file))
        }
    },
    _eventMap: {  },
    // 获取实例 - 虚构方法
    getInstance () {
        return im
    },
    // 初始化SDK
    initSDK (sdkAppID, sdkConfig = {}, callback = {}) {
        sdkAppID = sdkAppID || im.sdkAppId
        sdkConfig = sdkConfig || { logLevel: 0 }
        let _cb = res => {
            console.log(res)
            if (typeof callback === 'function') {
                setTimeout(() => callback(res), 0)
            }
            if (res.type && typeof res === 'object') {
                if (callback[res.type]) {
                    setTimeout(() => callback[res.type](res), 0)
                }
                if (im._eventMap[res.type]) {
                    im._eventMap[res.type].forEach(cb => {
                        setTimeout(() => cb(res), 0)
                    })
                }
            }
        }
        sdkwx.initSDK(sdkAppID, sdkConfig, _cb)
        im.addSimpleMsgListener(_cb)
        im.addAdvancedMsgListener(_cb)
        im.setConversationListener(_cb)
    },
    // 反初始化 SDK
    unInitSDK () {
        sdkwx.unInitSDK()
    },
    // 添加全局事件监听
    $on (eventType, callback) {
        im._eventMap[eventType] = im._eventMap[eventType] || []
        im._eventMap[eventType].push(callback)
    },
    // 删除全局事件监听
    $off (eventType, callback) {
        im._eventMap[eventType] = im._eventMap[eventType] || []
        let index = im._eventMap[eventType].indexOf(callback)
        if (index >= 0) {
            im._eventMap[eventType].splice(index, 1)
        }
    },
    // 设置基本消息（文本消息和自定义消息）的事件监听器
    addSimpleMsgListener (cb) {
        sdkwx.addSimpleMsgListener(cb)
    },
    // 移除基本消息（文本消息和自定义消息）的事件监听器
    removeSimpleMsgListener () {
        sdkwx.removeSimpleMsgListener()
    },
    // 登录
    login (userID, userSig, callback) {
        return im._p(next => {
            sdkwx.login(userID + '', userSig, callback || next)
        })
    },
    // 发送单聊（C2C）普通文本消息
    sendC2CTextMessage (text, userId, callback) {
        return im._p(next => {
            sdkwx.sendC2CTextMessage(text, userId, callback || next)
        })
    },
    // 发送单聊自定义（信令）消息（最大支持 8KB）
    sendC2CCustomMessage (customData = {}, userID, callback) {
        return im._p(next => {
            sdkwx.sendC2CCustomMessage(customData, userID, callback || next)
        })
    },
    // 获取聊天工具类 - 虚构方法
    getMessageManager () {
        return im
    },
    // 设置高级消息的事件监听器
    addAdvancedMsgListener (cb) {
        message.addAdvancedMsgListener(cb)
    },
    // 移除高级消息的事件监听器
    removeAdvancedMsgListener () {
        message.removeAdvancedMsgListener()
    },
    // 发送高级消息
    // offlinePushInfo = { title: string, desc: string, ext: string, iOSSound: string, androidOPPOChannelID: string, ignoreIOSBadge: boolean, disablePush: boolean }
    sendMessage (msg = null, receiver = null, groupID = null, priority = 1, onlineUserOnly = false, offlinePushInfo = {}, callback) {
        return im._p((next, reject) => {
            message.sendMessage(msg, receiver, groupID, priority, onlineUserOnly, offlinePushInfo, ret => {
                if (ret.type === 'onSuccess') {
                    let cb = callback || next
                    cb(ret)
                } else if (ret.type === 'onError') {
                    reject(ret)
                }
            })
        })
    },
    // 获取下载媒体消息
    DOWNLOAD_TYPE_SNAPSHOT: 0,
    DOWNLOAD_TYPE_FILE: 1,
    DOWNLOAD_TYPE_VIDEO: 2,
    DOWNLOAD_TYPE_AUDIO: 3,
    requestDownloadUrl (type, businessId = 0, uuid, callback) {
        return im._p(next => {
            message.requestDownloadUrl(type, businessId, uuid, callback || next)
        })
    },
    // 下载媒体消息
    downloadToFile (type, url, path, callback) {
        return im._p(next => {
            message.downloadToFile(type, url, path, callback || next)
        })
    },
    downloadSound (msgId, path, callback) {
        return im._p((next, reject) => {
            message.downloadSound(msgId, path, ret => {
                if (ret.type === 'onSuccess') {
                    let cb = callback || next
                    cb(ret)
                } else if (ret.type === 'onError') {
                    reject(ret)
                }
            })
        })
    },
    downloadSnapshot (msgId, path, callback) {
        return im._p(async (next, reject) => {
            let quitQueue = await imUtils.queueWait('txim.downloadSnapshot')
            message.downloadSnapshot(msgId, path, ret => {
                if (ret.type === 'onSuccess') {
                    let cb = callback || next
                    quitQueue()
                    cb(ret)
                } else if (ret.type === 'onError') {
                    quitQueue()
                    reject(ret)
                }
            })
        })
    },
    downloadVideo (msgId, path, callback) {
        return im._p((next, reject) => {
            message.downloadVideo(msgId, path, ret => {
                if (ret.type === 'onSuccess') {
                    let cb = callback || next
                    cb(ret)
                } else if (ret.type === 'onError') {
                    reject(ret)
                }
            })
        })
    },
    downloadFile (msgId, path, callback) {
        return im._p((next, reject) => {
            message.downloadFile(msgId, path, ret => {
                if (ret.type === 'onSuccess') {
                    let cb = callback || next
                    cb(ret)
                } else if (ret.type === 'onError') {
                    reject(ret)
                }
            })
        })
    },
    // 这仅仅是一个hack的方法，解决ios下面因为句柄释放问题导致文件丢失 inFile
    copyFileToFile (inFile) {
        if (plus.os.name.toLowerCase() === 'android') {
            return inFile
        }
        return new Promise(async resolve => {
            let getEntry = path => new Promise(next => plus.io.resolveLocalFileSystemURL(path, next, () => next(false)))
            let moveTo = (entry, dEntry, newName) => new Promise(next => entry.moveTo(dEntry, newName, next, () => next(false)))
            let copyName = inFile.split('/').pop()
            let docEntry = await getEntry('_doc')
            if (!docEntry) {
                resolve(inFile)
            }
            let inFileEntry = await getEntry(inFile)
            !inFileEntry && resolve(inFile)
            let ret = await moveTo(inFileEntry, docEntry, 'copy-' + copyName)
            inFileEntry.remove()
            !ret && resolve(inFile)
            // let cpFileEntry = await getEntry('_doc/' + 'copy-' + copyName)
            // !cpFileEntry && resolve(inFile)
            // ret = await moveTo(cpFileEntry, docEntry, copyName)
            resolve('_doc/copy-' + copyName)
        })
        // let fileArr = inFile.split('/')
        // fileArr[fileArr.length - 1] = 'copy-' + fileArr[fileArr.length - 1]
        // return new Promise(resolve => {
        //     uni.saveFile({
        //         tempFilePath: inFile,
        //         success: ({ savedFilePath }) => resolve(savedFilePath),
        //         fail: () => resolve(inFile)
        //     })
        // })
    },
    ELEM_TYPE_TEXT: 1,
    ELEM_TYPE_CUSTOMMSG: 2,
    ELEM_TYPE_IMAGE: 3,
    ELEM_TYPE_SOUND: 4,
    ELEM_TYPE_VIDEO: 5,
    ELEM_TYPE_FILE: 6,
    ELEM_TYPE_LOCATION: 7,
    ELEM_TYPE_FACE: 8,
    // 创建消息格式体
    _build_advanced_msg (elemType, elem) {
        return { elemType, elem }
    },
    // 创建文本消息 - 虚构方法
    createTextMessage (text) {
        return im._build_advanced_msg(im.ELEM_TYPE_TEXT, { text })
    },
    // 创建自定义消息
    createCustomMessage (data) {
        return im._build_advanced_msg(im.ELEM_TYPE_CUSTOMMSG, data)
    },
    // 创建图片消息（图片最大支持 28 MB）- 虚构方法
    createImageMessage (imagePath) {
        return im._build_advanced_msg(im.ELEM_TYPE_IMAGE, {
            imagePath: im._filePathToLocal(imagePath)
        })
    },
    // 创建语音消息（语音最大支持 28 MB） - 虚构方法
    createSoundMessage (soundPath, duration) {
        return im._build_advanced_msg(im.ELEM_TYPE_SOUND, {
            soundPath: im._filePathToLocal(soundPath),
            duration
        })
    },
    // 创建视频消息（视频最大支持 100 MB） - 虚构方法
    createVideoMessage (videoFilePath, type, duration, snapshotPath) {
        return im._build_advanced_msg(im.ELEM_TYPE_VIDEO, {
            videoFilePath: im._filePathToLocal(videoFilePath),
            type,
            duration,
            snapshotPath: im._filePathToLocal(snapshotPath)
        })
    },
    // 创建文件消息（文件最大支持 100 MB）- 虚构方法
    createFileMessage (filePath, fileName) {
        return im._build_advanced_msg(im.ELEM_TYPE_FILE, {
            filePath: im._filePathToLocal(fileName),
            fileName
        })
    },
    // 创建地理位置消息 - 虚构方法
    createLocationMessage (desc, longitude, latitude) {
        return im._build_advanced_msg(im.ELEM_TYPE_LOCATION, { desc, latitude, longitude })
    },
    // 创建表情消息 - 虚构方法
    createFaceMessage (index, data) {
        return im._build_advanced_msg(im.ELEM_TYPE_FACE, { index, data })
    },
    // 撤回消息
    revokeMessage (msg, callback) {
        return im._p(next => {
            message.revokeMessage(msg, callback || next)
        })
    },
    // 设置单聊消息已读
    markC2CMessageAsRead (userID, callback) {
        return im._p(next => {
            message.markC2CMessageAsRead(userID, callback || next)
        })
    },
    // 设置群组消息已读
    markGroupMessageAsRead (groupID, callback) {
        return im._p(next => {
            message.markGroupMessageAsRead(groupID, callback || next)
        })
    },
    // 获取单聊历史消息
    getC2CHistoryMessageList (userID, count = 20, lastMsg = null, callback) {
        return im._p(next => {
            message.getC2CHistoryMessageList(userID, count, lastMsg, callback || next)
        })
    },
    // 获取群组历史消息
    getGroupHistoryMessageList (groupID, count = 20, lastMsg = null, callback) {
        return im._p(next => {
            message.getGroupHistoryMessageList(groupID, count, lastMsg, callback || next)
        })
    },
    // 删除本地消息
    deleteMessageFromLocalStorage (msg, callback) {
        return im._p(next => {
            message.deleteMessageFromLocalStorage(msg, callback || next)
        })
    },
    // 获取会话工具类 - 虚构方法
    getConversationManager () {
        return im
    },
    // 设置会话监听器
    setConversationListener (cb) {
        conversation.setConversationListener(cb)
    },
    // 获取会话列表
    getConversationList (nextSeq = 0, count = 100, callback) {
        return im._p(next => {
            conversation.getConversationList(nextSeq, count, callback || next)
        })
    },
    // 删除会话
    deleteConversation (conversationID, callback) {
        return im._p(next => {
            conversation.deleteConversation(conversationID, callback || next)
        })
    },
    // setConversationDraft
    setConversationDraft (conversationID, draftText, callback) {
        return im._p(next => {
            conversation.setConversationDraft(conversationID, draftText, callback || next)
        })
    }
}

export default im
